package com.example.demo.Controller.Opus_Comment;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.demo.Entity.Opus.Opus;
import com.example.demo.Entity.UserInfo.Userinfo;
import com.example.demo.ServiceImpl.Opus.OpusServiceImpl;
import com.example.demo.ServiceImpl.Opus_Comment.OpusCommentServiceImpl;
import com.example.demo.Entity.Opus_Comment.OpusComment;
import com.example.demo.ServiceImpl.UserInfo.UserinfoServiceImpl;
import com.example.demo.Utils.JWTUtils.JWTUtils;
import com.example.demo.Utils.RedisUtils.RedisUtil;
import com.example.demo.Utils.Result.R;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/opusComment")
@CrossOrigin(origins = "*")
@Tag(name = "OpusCommentController", description = "OpusCommentController 相关接口")
public class OpusCommentController {

    @Resource
    private OpusCommentServiceImpl opusCommentService;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private UserinfoServiceImpl userinfoService;

    @Resource
    private OpusServiceImpl opusService;

    @Resource
    private RedisUtil redisUtil;

    @PostMapping
    @Operation(summary = "保存或更新 OpusComment 信息", description = "根据传入的 OpusComment 对象保存或更新信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "保存或更新成功", content = @Content(schema = @Schema(implementation = Boolean.class)))
    })
    public Boolean save(@RequestBody OpusComment opusComment, HttpServletRequest request) {
// 保存或更新数据后，删除相关缓存
        redisTemplate.delete("opusComment:all");
        redisUtil.deleteKeysStartingWith("opusComment");
        if (opusComment.getCommentUserId() == null) {
            String token = request.getHeader("Authorization");
            Integer userId = Integer.parseInt(JWTUtils.getUserIDFromToken(token));
            opusComment.setCommentUserId(userId);
            opusComment.setCreateTime(new Date());
        }
        return opusCommentService.saveOrUpdate(opusComment);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "根据 ID 删除 OpusComment 信息", description = "根据传入的 ID 删除对应的 OpusComment 信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "删除成功", content = @Content(schema = @Schema(implementation = Boolean.class)))
    })
    public Boolean delete(@PathVariable(value = "id") Integer id) {
// 删除数据后，删除相关缓存
        redisTemplate.delete("opusComment:all");
        redisTemplate.delete("opusComment:id:" + id);
        redisUtil.deleteKeysStartingWith("opusComment");
        return opusCommentService.removeById(id);
    }

    @GetMapping
    @Operation(summary = "获取所有 OpusComment 信息", description = "获取所有 OpusComment 的列表信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(schema = @Schema(implementation = R.class)))
    })
    public R findAll() {
        String key = "opusComment:all";
        List<OpusComment> opusCommentList = (List<OpusComment>) redisTemplate.opsForValue().get(key);
        if (opusCommentList == null) {
            opusCommentList = opusCommentService.list();
            redisTemplate.opsForValue().set(key, opusCommentList, 60, TimeUnit.MINUTES);
        }
        return R.ok().put("opusCommentList", opusCommentList);
    }

    @GetMapping("/{id}")
    @Operation(summary = "根据 ID 获取 OpusComment 信息", description = "根据传入的 ID 获取对应的 OpusComment 信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(schema = @Schema(implementation = R.class)))
    })
    public R findOne(@PathVariable(value = "id") Integer id) {
        String key = "opusComment:id:" + id;
        OpusComment opusComment = (OpusComment) redisTemplate.opsForValue().get(key);
        if (opusComment == null) {
            opusComment = opusCommentService.getById(id);
            if (opusComment != null) {
                redisTemplate.opsForValue().set(key, opusComment, 60, TimeUnit.MINUTES);
            }
        }
        return R.ok().put("opusComment", opusComment);
    }

    @GetMapping("/page")
    @Operation(summary = "分页获取 OpusComment 信息", description = "根据传入的页码和每页数量分页获取 OpusComment 信息")
    @ApiResponses(value = {
            @ApiResponse(responseCode = "200", description = "获取成功", content = @Content(schema = @Schema(implementation = R.class)))
    })
    @Parameter(name = "pageNum", in = ParameterIn.QUERY, description = "页码", required = true)
    @Parameter(name = "pageSize", in = ParameterIn.QUERY, description = "每页数量", required = true)
    @Parameter(name = "keyword", in = ParameterIn.QUERY, description = "搜索关键字")
    public R findPage(@RequestParam(value = "pageNum") Integer pageNum,
                      @RequestParam(value = "pageSize") Integer pageSize,
                      @RequestParam(value = "keyword", required = false) String keyword) {
        String key = "opusComment:page:" + pageNum + ":" + pageSize + ":" + keyword;
        Page<OpusComment> opusCommentPage = (Page<OpusComment>) redisTemplate.opsForValue().get(key);
        if (opusCommentPage == null) {
            if (keyword != null && !keyword.isEmpty()) {
                LambdaQueryWrapper<OpusComment> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.like(OpusComment::getWords, keyword);
                LambdaQueryWrapper<Userinfo> userinfoQueryWrapper = new LambdaQueryWrapper<>();
                userinfoQueryWrapper.like(Userinfo::getNickname, keyword);
                List<Userinfo> userinfoList = userinfoService.list(userinfoQueryWrapper);
                List<Integer> userIds = new ArrayList<>();
                if (userinfoList != null && !userinfoList.isEmpty()) {
                    for (Userinfo userinfo : userinfoList) {
                        userIds.add(userinfo.getUserId());
                    }
                }
                if (!userIds.isEmpty()) {
                    queryWrapper.or().in(OpusComment::getCommentUserId, userIds);
                }
                LambdaQueryWrapper<Opus> opusLambdaQueryWrapper = new LambdaQueryWrapper<>();
                opusLambdaQueryWrapper.like(Opus::getOpusTitle, keyword);
                opusLambdaQueryWrapper.or().like(Opus::getOpusHtml, keyword);
                List<Opus> opusList = opusService.list(opusLambdaQueryWrapper);
                List<Integer> opusIds = new ArrayList<>();
                if (opusList != null && !opusList.isEmpty()) {
                    for (Opus opus : opusList) {
                        opusIds.add(opus.getOpusId());
                    }
                }
                if (!opusIds.isEmpty()) {
                    queryWrapper.or().in(OpusComment::getOpusId, opusIds);
                }
            }
            opusCommentPage = opusCommentService.page(new Page<>(pageNum, pageSize));
            redisTemplate.opsForValue().set(key, opusCommentPage, 60, TimeUnit.MINUTES);
        }
        List<String> OpusNameList = new ArrayList<>();
        List<String> UserNameList = new ArrayList<>();
        for (OpusComment opusComment : opusCommentPage.getRecords()) {
            Opus opus = opusService.getById(opusComment.getOpusId());
            LambdaQueryWrapper<Userinfo> userinfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userinfoLambdaQueryWrapper.like(Userinfo::getUserId, opusComment.getCommentUserId());
            Userinfo userinfo = userinfoService.getOne(userinfoLambdaQueryWrapper);
            if (userinfo != null) {
                UserNameList.add(userinfo.getNickname());
            } else {
                UserNameList.add("");
            }
            if (opus != null) {
                OpusNameList.add(opus.getOpusTitle());
            } else {
                OpusNameList.add("");
            }
        }
        return R.ok().put("opusCommentPage", opusCommentPage).put("OpusNameList", OpusNameList).put("UserNameList", UserNameList);
    }
}